package com.zc.app.shiro.dao;

import com.zc.app.shiro.peer.RolePeer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;


//@Repository
public class RoleDaoImpl implements RoleDao {

//    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public RolePeer createRole(final RolePeer role) {
        final String sql = "insert into sys_role(role, description, resource_ids, available) values(?,?,?,?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
                int count = 1;
                psst.setString(count++, role.getRole());
                psst.setString(count++, role.getDescription());
                psst.setString(count++, role.getResourceIdsStr());
                psst.setBoolean(count++, role.getAvailable());
                return psst;
            }
        }, keyHolder);
        role.setId(keyHolder.getKey().longValue());
        return role;
    }

    @Override
    public RolePeer updateRole(RolePeer role) {
        final String sql = "update sys_role set role=?, description=?, resource_ids=?, available=? where id=?";
//        jdbcTemplate.update(
//                sql,
//                role.getRole(), role.getDescription(), role.getResourceIdsStr(), role.getAvailable(), role.getId());
//        return role;
        return null;
    }

    public void deleteRole(Long roleId) {
        final String sql = "delete from sys_role where id=?";
//        jdbcTemplate.update(sql, roleId);
    }


    @Override
    public RolePeer findOne(Long roleId) {
        final String sql = "select id, role, description, resource_ids as resourceIdsStr, available from sys_role where id=?";
//        List<RolePeer> roleList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(RolePeer.class), roleId);
//        if(roleList.size() == 0) {
            return null;
//        }
//        return roleList.get(0);
    }

    @Override
    public List<RolePeer> findAll() {
        final String sql = "select id, role, description, resource_ids as resourceIdsStr, available from sys_role";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper(RolePeer.class));
    }

}
